import React, { useState } from 'react';
import { Form, Input, Button, Card, message, Alert } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { useNavigate, Link } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useAuth } from '../contexts/AuthContext';

const Login: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const { login } = useAuth();
  const navigate = useNavigate();
  const { t } = useTranslation();

  const getErrorMessage = (error: any): string => {
    // 网络错误
    if (!error.response) {
      if (error.code === 'ECONNREFUSED' || error.message?.includes('Network Error')) {
        return t('auth.errorMessages.connectionRefused');
      }
      if (error.code === 'ETIMEDOUT' || error.message?.includes('timeout')) {
        return t('auth.errorMessages.timeout');
      }
      return t('auth.errorMessages.networkError');
    }

    // HTTP 状态码错误
    const status = error.response?.status;
    const message = error.response?.data?.message || '';

    switch (status) {
      case 401:
        // 根据后端返回的具体消息显示不同的错误
        if (message.includes('AppUsers cannot login')) {
          return t('auth.errorMessages.appUserCannotLogin');
        }
        if (message.includes('Invalid username or password')) {
          return t('auth.errorMessages.invalidCredentials');
        }
        return t('auth.errorMessages.unauthorized');
      case 403:
        return t('auth.errorMessages.accountLocked');
      case 404:
        return t('auth.errorMessages.userNotFound');
      case 500:
      case 502:
      case 503:
        return t('auth.errorMessages.serverError');
      default:
        // 尝试从后端消息中提取错误信息
        if (message) {
          // 映射常见的后端错误消息
          if (message.includes('Invalid username or password')) {
            return t('auth.errorMessages.invalidCredentials');
          }
          if (message.includes('AppUsers cannot login')) {
            return t('auth.errorMessages.appUserCannotLogin');
          }
          return message;
        }
        return t('auth.errorMessages.unknownError');
    }
  };

  const onFinish = async (values: { username: string; password: string }) => {
    setLoading(true);
    setErrorMessage(null);
    
    try {
      await login(values.username, values.password);
      message.success(t('auth.loginSuccess'));
      navigate('/');
    } catch (error: any) {
      const errorMsg = getErrorMessage(error);
      setErrorMessage(errorMsg);
      message.error(errorMsg);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh', backgroundColor: '#f0f2f5' }}>
      <Card title={t('auth.loginTitle')} style={{ width: 400 }}>
        {errorMessage && (
          <Alert
            message={errorMessage}
            type="error"
            showIcon
            closable
            onClose={() => setErrorMessage(null)}
            style={{ marginBottom: 24 }}
          />
        )}
        <Form
          name="login"
          onFinish={onFinish}
          autoComplete="off"
          layout="vertical"
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: t('auth.usernameRequired') }]}
          >
            <Input
              prefix={<UserOutlined />}
              placeholder={t('auth.usernamePlaceholder')}
              size="large"
              autoComplete="username"
            />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[{ required: true, message: t('auth.passwordRequired') }]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder={t('auth.passwordPlaceholder')}
              size="large"
              autoComplete="current-password"
            />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading} block size="large">
              {t('auth.login')}
            </Button>
          </Form.Item>

          <div style={{ textAlign: 'center' }}>
            {t('auth.noAccount')} <Link to="/register">{t('auth.registerNow')}</Link>
          </div>
        </Form>
      </Card>
    </div>
  );
};

export default Login;
